package iot.wlink.network.protocols.mqtt;

import iot.wlink.network.devices.bean.Identity;
import iot.wlink.network.devices.manager.AbstractDeviceManager;
import iot.wlink.network.payload.down.DownPayload;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.core.server.MqttServer;

import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * @author : willian fu
 * @date : 2021/8/21
 */
@Slf4j
@Component
public class MqttDeviceManager extends AbstractDeviceManager {

    @Setter
    private MqttServer server;

    @Override
    public void disconnect(String uid) {
        try {
            server.getTioServer().getServerSocketChannel().close();
        } catch (IOException e) {
            log.error("主动断开[{}]的MQTT连接异常", uid, e);
        }
    }

    @Override
    public String getDeviceRemoteIp(String uid) {
        return "";
    }

    @Override
    public void sendData(String uid, DownPayload payload) {
        try {
            ByteBuffer buffer = ByteBuffer.wrap(encode(uid, payload));
            server.publish(uid, "", buffer);
        } catch (Exception e) {
            log.error("MQTT 发送数据到[{}]异常", uid, e);
        }
    }

    @Override
    public void authentication(Identity identity) {

    }

    @Override
    public void authentication(String token) {

    }

}
